public without sharing class MearsureCalcUtil {


    public MearsureCalcUtil(String trmId  ){
        
    }

    public static  void calcTasks(String trmId ){
        /*
    	Map<String,TaskBean>  eMap =  new Map<String,TaskBean>();

        TaskRelatedMeasure__c  trm = [select Id,StartDate__c,RelatedType__c,Standers__c ,MeasureCalc__c from TaskRelatedMeasure__c where Id =: trmId];
	       
        String  year = String.valueOf(trm.StartDate__c.year())+'年';
        Set<String> month = new Set<String>();

        for(Integer i = trm.StartDate__c.month() ; i <=12 ; i ++){
            
            month.add(String.valueOf(i));
        }
		for(TaskAmount__c ta : [select Id,Year__c,Cost__c,Month__c,Brand__c,AssignAmount__c,Category1__c,Category2__c
		 from TaskAmount__c where Standers__c =: trm.Standers__c and Origin__c !='销售政策' and (Year__c >:year Or (Year__c =:year and Month__c in: month)) ]){

			String key = ta.Category1__c +'_'+ta.Brand__c +'_'+ta.Category2__c + '_'+ta.Year__c + '_'+ ta.Month__c;
			eMap.put(key, new TaskBean(ta));
           // System.debug(key);

		}
       

        //新关联的测算拆分的任务量
		Map<String,TaskBean>  addMap =  caMeasure(trm.MeasureCalc__c, trm.StartDate__c);
        //将新拆分的任务量增加到原来的任务量中
		for (String key : addMap.keySet() ) {
			TaskBean t = null;
			if(eMap.containsKey(key)){
				TaskBean at = addMap.get(key);//
				t = eMap.get(key);

				if(trm.RelatedType__c == 'add'){
                    t.taskAmount = t.taskAmount + at.taskAmount;
                    t.cost = t.cost + at.cost ;
                }
				if(trm.RelatedType__c == 'append'){
                    t.taskAmount =  at.taskAmount;
                    t.cost =  at.cost;
                }

			}else{
				t = addMap.get(key);
			}

			eMap.put(key, t);
		}
    	

    	List<TaskAmount__c> tList = new List<TaskAmount__c>();
    	for (TaskBean t : eMap.values() ) {
    		tList.add(genFromBean(t,trm.Standers__c,trm.MeasureCalc__c));

    	}
    	if(tList.size() >0)upsert tList;
        */
    	
    }
    public static TaskAmount__c genFromBean(TaskBean b,String csId ,String mcid ){
    	TaskAmount__c t = new TaskAmount__c();
        t.Id = b.tid;
    	t.Year__c = b.year;
    	t.Month__c = b.month;
    	t.Category1__c = b.cate1;
    	t.Category2__c = b.cate2;
    	t.Brand__c = b.brand;
    	t.AssignAmount__c = b.taskAmount;
    	t.Standers__c  = csId;
        t.MeasureCalc__c = mcid ;
        t.SubProfit__c = b.subprofit;
        t.GroupProfit__c = b.groupprofit;
        //t.Cost__c = b.cost;
        t.Origin__c = '测算';
    	return t;

    }
    /*
    //计算新的测算的任务量 并拆分
    public static  List<MiddleBean>   caMeasure (String mcid){
    	Measure_Calculate__c mc = [select Id ,SampleIncreaseRatio__c,CoopYear__c from Measure_Calculate__c where Id=:mcid];

    	List<Measure_Calculate_Product__c> mpList = [select Id,Product__c,Product__r.Category1__c,TaxRate__c,SampleNum1__c,
    	TestNum__c,SalesPriceWT__c,Product__r.Category2__c,Product__r.SerialNo__c ,Product__r.Brand__c,SubInstCost__c,InstCost__c
    	 from Measure_Calculate_Product__c where  Measure_Calculate__c =:mcid and IsEquipRelated__c = false];
       	Integer coopYear = Integer.valueOf(mc.CoopYear__c.substring(0, mc.CoopYear__c.length() - 1));

        Map<String,Map<Integer,Decimal>> proCostMap = new Map<String,Map<Integer,Decimal>>();
        Map<String,Map<Integer,Decimal>> proGroupCostMap = new Map<String,Map<Integer,Decimal>>();
    	Map<String,Map<Integer,Decimal>> proSalesMap = new Map<String,Map<Integer,Decimal>>();

    	for ( Measure_Calculate_Product__c mp :mpList ) {
    		Map<Integer,Decimal> yearMap = null;
            Map<Integer,Decimal> yearCostMap = null;
            Map<Integer,Decimal> yearGroupCostMap = null;

            //System.debug( mp.Product__r.Category1__c);
           // System.debug( mp.Product__c);

    		String cate11 = mp.Product__r.Category1__c == null ? String.valueOf(mp.Product__c) : mp.Product__r.Category1__c;
    		String cate22  = mp.Product__r.Category2__c == null ? String.valueOf(mp.Product__c ): mp.Product__r.Category2__c;
    		String brand11 = mp.Product__r.Brand__c == null ? String.valueOf(mp.Product__c ) : mp.Product__r.Brand__c;

    		String key = cate11+'_'+brand11 +'_'+cate22;
            yearGroupCostMap = proGroupCostMap.get(key) == null ? new Map<Integer,Decimal>() : proGroupCostMap.get(key);

            yearCostMap = proCostMap.get(key) == null ? new Map<Integer,Decimal>() : proCostMap.get(key);
    		yearMap = proSalesMap.get(key) == null ? new Map<Integer,Decimal>() : proSalesMap.get(key);
    		for ( Integer i = 1 ;i <= coopYear ; i ++ ) {
    			
    			Decimal sample = CalcSamples(getDecimalValue(mp.SampleNum1__c),getDecimalValue(mc.SampleIncreaseRatio__c),i);
    			Decimal sale = 0;

                Decimal subcost = 0;
                Decimal groupcost = 0 ; 

    			if( getSpecialProductSet().contains(mp.Product__r.SerialNo__c) ){//特殊产品
    				sale = specialPrice(sample);

    			}else{
					sale = CalcSales(getDecimalValue(mp.SalesPriceWT__c),getDecimalValue(mp.TestNum__c),sample);
    			}

                subcost =  CalcCost(getDecimalValue(mp.SubInstCost__c),getDecimalValue(mp.TestNum__c),sample);
                subcost =  yearCostMap.get(i) == null ?  subcost : yearCostMap.get(i) + subcost;
                System.debug(subcost);

                groupcost =  CalcCost(getDecimalValue(mp.InstCost__c),getDecimalValue(mp.TestNum__c),sample);

                groupcost =  yearGroupCostMap.get(i) == null ?  groupcost : yearGroupCostMap.get(i) + groupcost;
                System.debug(groupcost);


    			Decimal sales =  yearMap.get(i) == null ?  sale :   yearMap.get(i) + sale;
    			yearMap.put(i, sales);
    			yearCostMap.put(i, subcost);
                yearGroupCostMap.put(i,groupcost);

    		}
    		    proSalesMap.put(key , yearMap);
                proCostMap.put(key , yearCostMap);
                proGroupCostMap.put(key,yearGroupCostMap);

       
    	}
         List<MiddleBean> resL = new List<MiddleBean>();
            for (String key :proSalesMap.keySet() ) {
                List<String> keys = key.split('_');
                MiddleBean mb = new MiddleBean();
                mb.brand  = keys[1];
                mb.cate1 = keys[0];
                mb.cate2 = keys[2];
                mb.amountMap = proSalesMap.get(key);
                mb.subcostMap = proCostMap.get(key);
                mb.groupcostMap = proGroupCostMap.get(key);
                resL.add(mb) ;
        }
        return resL;
    	//return dispatchTask(proSalesMap,proCostMap,proGroupCostMap, startDate,coopYear);
    }*/

    
    //按 一级+二级分类 按月拆分销售额 为任务量
    public  static  List<TaskBean> dispatchTask(Map<String,Map<Integer,Decimal>> proSalesMap,Map<String,Map<Integer,Decimal>> proCostMap,Map<String,Map<Integer,Decimal>> proGroupCostMap,Date startDate, Integer coopYear){
        

    	Integer year = startDate.year();
    	Integer month = startDate.month();

    	List<TaskBean> resTaskMap = new List<TaskBean>  ();
    	for (String key :proSalesMap.keySet() ) {
    	//一级分类 + 二级分类
    		 Map<String,Decimal>  tasks = new Map<String,Decimal>();

    		Integer startYear = year;
    		Integer startMonth = month;

    		for (Integer i= 1 ;i <= coopYear ; i ++ ) {//年
    			for(Integer j = 0 ; j < 12; j++){
    				Decimal  res  = 0;
                    Decimal  cost  = 0;
                    Decimal groupcost = 0 ;
    				Decimal  y = startYear - year ;
    				String ym = String.valueOf(startYear) +'_'+String.valueOf(startMonth);

    				if(month == 1){
    					 res = (proSalesMap.get(key).get(Integer.valueOf(y+1)) / 12 ).setscale(8) ;
                         cost= (proCostMap.get(key).get(Integer.valueOf(y+1)) / 12).setscale(8) ;
                         groupcost= (proGroupCostMap.get(key).get(Integer.valueOf(y+1)) / 12).setscale(8) ;
    				}else{
    					if( y == 0   ){
    						res = (proSalesMap.get(key).get(Integer.valueOf(y+1)) / 12).setscale(8) ;
                            cost = (proCostMap.get(key).get(Integer.valueOf(y+1)) / 12).setscale(8) ;
                            groupcost = (proGroupCostMap.get(key).get(Integer.valueOf(y+1)) / 12).setscale(8) ;
    					} else if(y == coopYear){
    						res = (proSalesMap.get(key).get(Integer.valueOf(y)) / 12 ).setscale(8);
                            cost = (proCostMap.get(key).get(Integer.valueOf(y)) / 12).setscale(8) ;
                            groupcost = (proGroupCostMap.get(key).get(Integer.valueOf(y)) / 12).setscale(8) ;
    					}else{
    						Decimal dpoint =Math.ceil(((startMonth + startYear * 12 -  year * 12 - month) -(12 - month +1) +1 )/12.0) ;
                            res = (((month - 1) / 12.0 * proSalesMap.get(key).get(Integer.valueOf(dpoint))+(12-month +1) / 12.0 * proSalesMap.get(key).get(Integer.valueOf(dpoint+1)) ) / 12 ).setscale(8);
    						cost = (((month - 1) / 12.0 * proCostMap.get(key).get(Integer.valueOf(dpoint))+(12-month +1) / 12.0 * proCostMap.get(key).get(Integer.valueOf(dpoint+1)) ) / 12 ).setscale(8);
                            groupcost = (((month - 1) / 12.0 * proGroupCostMap.get(key).get(Integer.valueOf(dpoint))+(12-month +1) / 12.0 * proGroupCostMap.get(key).get(Integer.valueOf(dpoint+1)) ) / 12 ).setscale(8);
    					}
	    					  				
    				}
    				TaskBean t = new TaskBean(key,startYear,startMonth,res,cost,groupcost  );
                    //key+'_'+startYear+'年_'+startMonth,
    				resTaskMap.add( t );
    					startMonth+= 1;
		    			if(startMonth > 12){
		    				startMonth = 1;
		    				startYear += 1;
		    			}
    			}
    		}
    		

    	}
    	return resTaskMap;
    	//System.debug(JSON.serialize(resTaskMap));

    }
/*
    //特殊的产品
    private static Set<String> getSpecialProductSet (){

    	 Set<String> t = new Set<String>();
    	 t.add('986-8036');
    	 t.add('986-8034');
    	 t.add('986-8038');
    	 return t;
    }
    ///特殊价格 货号为这几个的产品
    private static Decimal specialPrice(Decimal val) {
	    if (val == 0 || val == null) return 0;
	    Decimal t = val / 312;
	    Decimal p = 0 ;
	    if (t > 0 && t < 60) {
	        p = 1.63;
	    }
	    if (t >= 60 && t < 70) {
	        p = 1.47;
	    }
	    if (t >= 70 && t < 80) {
	        p = 1.36;
	    }
	    if (t >= 80 && t < 90) {
	        p = 1.28;
	    }
	    if (t >= 90 && t < 100) {
	        p = 1.21;
	    }
	    if (t >= 100 && t < 120) {
	        p = 1.16;
	    }
	    if (t >= 120 && t < 150) {
	        p = 1.08;
	    }
	    if (t >= 150 && t < 180) {
	        p = 1.01;
	    }
	    if (t >= 180 && t < 200) {
	        p = 0.95;
	    }
	    if (t >= 200) {
	        p = 0.93;
	    }
	    return val * p;
	}
    ///计算标本量
    private static Decimal CalcSamples(Decimal s1 ,Decimal rito,Integer year ){
    	if(year > 1){
    		return CalcSamples(s1 ,rito ,year -1) * (1+rito/100);
    	}else{	
    		return s1;
    	}
    }
    ///计算销售额
    private static Decimal  CalcSales(Decimal price ,Decimal testnum ,Decimal sample){
    	
    	if(testnum == 0)return 0; 
    	return  (price / testnum  * sample /10000.0);
    }
    ///计算成本
    private static Decimal CalcCost (Decimal cost ,Decimal testnum ,Decimal sample){

        if(testnum == 0) return 0;
        return (cost /testnum * sample /10000.0);

    }
    //转换为数字
    private static Decimal getDecimalValue(Object o){

    	if(o == null) return 0;
    	try{
    		return Decimal.valueOf(String.valueOf(o));
    	}catch(Exception e){
    		return 0;
    	}
    }

    public class MiddleBean{
        public String brand;
        public String cate1 ;
        public String cate2 ; 

        public  Map<Integer,Decimal> amountMap ; 
        public  Map<Integer,Decimal> subcostMap ;
        public  Map<Integer,Decimal>  groupcostMap ;  
       
    }
    */

    public  Class TaskBean{
        public String tid;
    	public String cate1 ;//分类
    	public String year ;//年
    	public String month;//月
    	public Decimal taskAmount ;//任务量
    	public String cate2;
    	public String brand ;
        public Decimal subprofit ;
        public Decimal groupprofit ;

    	public TaskBean(TaskAmount__c ta){
            tid = ta.Id;
    		cate1 = ta.Category1__c;
    		cate2 = ta.Category2__c;
    		month = ta.Month__c;
    		year = ta.Year__c;
    		brand = ta.Brand__c;
    		taskAmount = ta.AssignAmount__c;
            subprofit = ta.SubProfit__c;
            groupprofit = ta.GroupProfit__c;

           // cost = ta.Cost__c == null ? 0 : ta.Cost__c;

    	}
        public TaskBean(Map<String,Object> to){
            tid = to.get('tid') == null ? null : String.valueOf(to.get('tid')).trim();
            cate1 = to.get('cate1') == null ? null : String.valueOf(to.get('cate1')).trim();
            cate2 = to.get('cate2') == null ? null : String.valueOf(to.get('cate2')).trim();
            month = to.get('month') == null ? null : String.valueOf(to.get('month')).trim();
            year = to.get('year') == null ? null : String.valueOf(to.get('year')).trim();
            brand = to.get('brand') == null ? null : String.valueOf(to.get('brand')).trim();
            taskAmount = to.get('taskAmount') == null ? null : Decimal.valueOf(String.valueOf(to.get('taskAmount')).trim());
           // cost = to.get('cost') == null ? null : Decimal.valueOf(String.valueOf(to.get('cost')).trim());
            subprofit = to.get('subprofit') == null ? null : Decimal.valueOf(String.valueOf(to.get('subprofit')).trim());
            groupprofit = to.get('groupprofit') == null ? null : Decimal.valueOf(String.valueOf(to.get('groupprofit')).trim());

        }
    	public TaskBean( String key ,Integer y ,Integer m , Decimal amount ,Decimal c,Decimal gc ){

    		String [] keys = key.split('_');
    		cate1 = keys[0];
    		brand = keys[1];
    		cate2 = keys[2];
    		year = String.valueOf(y)+'年';
    		month = String.valueOf(m);
    		taskAmount = amount;
            subprofit = amount - c;
            groupprofit = amount - gc;

    	}



    }
}